import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { ShareInfo, ShareStats, ShareFilter } from '@/types/share'
import type { ApiResponse, PageResponse } from '@/types/api'
import { getShareList, getShareStats, deleteShare, disableShare, enableShare } from '@/api/modules/share'

export const useShareStore = defineStore('share', () => {
  // 状态
  const shares = ref<ShareInfo[]>([])
  const stats = ref<ShareStats | null>(null)
  const loading = ref(false)

  const filters = ref<ShareFilter>({
    keyword: '',
    status: 'all',
    dateRange: null
  })
  const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // actions
  const initShareData = async () => {
    loading.value = true
    try {
      await Promise.all([
        fetchShareList(),
        fetchShareStats()
      ])
    } finally {
      loading.value = false
    }
  }

  const fetchShareList = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.value.currentPage - 1,
        size: pagination.value.pageSize,
        ...filters.value
      }
      const response = await getShareList(params)
      shares.value = response.data.content
      pagination.value.total = response.data.totalElements
    } finally {
      loading.value = false
    }
  }

  const fetchShareStats = async () => {
    const response = await getShareStats()
    stats.value = response.data
  }

  const updateFilters = async (newFilters: Partial<ShareFilter>) => {
    filters.value = { ...filters.value, ...newFilters }
    pagination.value.currentPage = 1
    await fetchShareList()
  }



  const deleteShareById = async (id: number) => {
    try {
      await deleteShare(id)
      await Promise.all([fetchShareList(), fetchShareStats()])
      return { success: true, message: '分享删除成功' }
    } catch (error: any) {
      return { success: false, message: error.message || '删除失败' }
    }
  }

  const disableShareById = async (id: number) => {
    try {
      await disableShare(id)
      await Promise.all([fetchShareList(), fetchShareStats()])
      return { success: true, message: '分享已禁用' }
    } catch (error: any) {
      return { success: false, message: error.message || '禁用失败' }
    }
  }

  const enableShareById = async (id: number) => {
    try {
      await enableShare(id)
      await Promise.all([fetchShareList(), fetchShareStats()])
      return { success: true, message: '分享已启用' }
    } catch (error: any) {
      return { success: false, message: error.message || '启用失败' }
    }
  }

  return {
    // 状态
    shares,
    stats,
    loading,
    filters,
    pagination,
    // actions
    initShareData,
    fetchShareList,
    fetchShareStats,
    updateFilters,
    deleteShare: deleteShareById,
    disableShare: disableShareById,
    enableShare: enableShareById
  }
}) 